import React, { Component, forwardRef } from 'react';
import E from 'wangeditor';
import './index.css';
import axios from 'axios';
import OSS from 'ali-oss';
import { uploadImgAccept, highConfig, middleConfig, lowConfig } from './config';
function getToken() {
    return axios.get('/api/gongyong/api/v1/oss/ossToken');
}

class Editor extends Component {
    constructor(props) {
        super(props);
    }
    state = {
        count: 0,
        isOut: false,   //输入字符是否超过最大值
        html: ''
    }
    componentDidMount() {
        this.init();
    }
    componentWillReceiveProps(nextProps) {
        if (nextProps && nextProps.oss) {
            this.client = nextProps.oss;
        }
    }
    componentWillUnmount(){
        this.editor=null;
        this.client=null;
    }
    //获取oss实例
    getToken = async () => {
        let res = await getToken();
        if (res) {
            let { data: { result } } = res;
            let client = new OSS({
                region: "oss-cn-beijing",
                accessKeyId: result.accessKeyId,
                accessKeySecret: result.keySecret,
                stsToken: result.token,
                bucket: result.bucket,
                secure: true
            });
            this.client = client;
        }
    }
    //change
    change = (currentCount, maxCount, html) => {
        currentCount > maxCount ? this.setState({ isOut: true, count: currentCount, html }) : this.setState({ isOut: false, count: currentCount, html });
    }
    //设置oss实例
    setClient = () => {
        let { oss } = this.props;
        oss ? this.client = oss : this.getToken();   //判断是否有oss实例传进来，如果有就用传入的，没有就自己new一个
    }
    //设置内容
    setValue(val) {
        this.editor.txt.html(val);  //设置富文本内容
    }
    //初始化
    init = () => {
        const { html, height, isFocus = true, placeholder, zIndex, configList = highConfig, maxCount, value, onChange, uploadImgMaxLength ,mountedNode} = this.props;
        const editor = new E(`#${mountedNode}`);    //获取富文本实例
        this.editor = editor;
        editor.config.height = height;
        editor.config.placeholder = placeholder;
        zIndex && (editor.config.zIndex = zIndex);
        editor.config.focus = isFocus;
        editor.config.onchange = (html) => {
            let l = editor.txt.text().trim().length;
            let v = html.trim();
            onChange && onChange(v);
            this.change(l, maxCount, v);
        };
        this.setClient();
        editor.config.menus = configList.menu; //配置菜单
        editor.config.showFullScreen = configList.isFullScreen;  //配置是否可以全屏
        editor.config.uploadImgAccept = uploadImgAccept;   //可上传图片的文件类型
        editor.config.uploadImgMaxLength = uploadImgMaxLength;  //限制一次能上传几张图片
        editor.config.customUploadImg = (resultFiles, insertImgFn) => {  //自定义上传图片
            Array.from(resultFiles).forEach(file => {
                let key = Math.random().toString().substr(3, 5) + new Date() * 1;
                if (this.client) {
                    this.client.put(key, file).then(res => {
                        const { url } = res;
                        insertImgFn(url);
                    })
                }
            })
        }
        editor.create();
        this.setValue(html ? html : value ? value : '');
        console.log(document.getElementById(mountedNode))
    }
    //清空富文本内容
    clear = () => {
        this.editor.txt.clear();
    }
    //全屏
    fullScreen = () => {
        this.editor.fullScreen();
    }
    //取消全屏
    unFullScreen = () => {
        this.editor.unFullScreen();
    }
    //禁用
    disable = () => {
        this.editor.disable();
    }
    //接触禁用
    enable = () => {
        this.editor.enable();
    }
    render() {
        const { count } = this.state;
        const { maxCount, isStat,mountedNode } = this.props;
        console.log(maxCount,isStat)
        return <div className='my_editor'>
            <div id={`${mountedNode}`}>
            </div>
            {
                isStat ? <div className='count'>
                    <span className={count > maxCount ? 'out_active' : ''}>{count}</span>/{maxCount}
                </div> : null
            }
        </div>
    }
}
Editor.defaultProps = {
    html: '',
    height: 240,
    isFocus: false,
    placeholder: '',
    maxCount: 2000,
    uploadImgMaxLength: 5,
    isStat: false
}

export default Editor
export const HighEditor = forwardRef((props, ref) => {
    return <Editor {...props} ref={ref} configList={highConfig} />
})
export const MiddleEditor = forwardRef((props, ref) => {
    return <Editor {...props} ref={ref} configList={middleConfig} />
})
export const LowEditor = forwardRef((props, ref) => {
    return <Editor {...props} ref={ref} configList={lowConfig} />
})



class Preview extends Component {

    render() {
        return (
            <div style={{padding:10,overflow:'auto'}}>
                <div className='text_desc'>
                    高配的示例
                    
                </div>
               
                   <HighEditor mountedNode={'ditor11'} html ={'高配的示例'} placeholder='请输入内容' isStat={true} maxCount={500}/>
              
                
                <div className='text_desc'>
                中配的示例
                </div>
      
                   <MiddleEditor  mountedNode={'ditor22'} html ={'中配的示例'}  placeholder='请输入呃呃呃内容' isStat={true}/>
             
               
                <div className='text_desc'>
                 低配的示例
                </div>
         
                   <LowEditor   mountedNode={'ditor33'} html ={'低配的示例'}  placeholder='请输入内容都是是' isStat={true}/>
         
             
            </div>
        )
    }
}

export const EditorPreview = Preview